<template>
  <a-tabs v-model="activeKey"
          hideAdd
          :type="type"
          @change="onTabChange"
          @edit="onEdit">
    <!-- :tab="getTabTitle(page)" -->
    <a-tab-pane v-for="page in pages"
                :forceRender="true"
                :key="page.name"
                :closable="pages.length > 1">
      <a-dropdown slot="tab"
                  :trigger="['contextmenu']">
        <span style="display:inline-block; height: 100%">
          {{ getTabTitle(page) }}
        </span>
        <a-menu slot="overlay">
          <a-menu-item key="refresh"
                       @click="refresh(page)">
            <a-icon type="reload" />
            刷新
          </a-menu-item>
          <a-menu-item @click="onEdit(page.name, 'remove')">
            <a-icon type="close" />
            关闭
          </a-menu-item>
          <a-menu-item @click="closeOther(page)">
            <a-icon type="close-circle" />
            关闭其他
          </a-menu-item>
          <a-menu-item @click="closeRight(page)">
            <a-icon type="arrow-right" />
            关闭右侧
          </a-menu-item>
          <a-menu-item @click="closeLeft(page)">
            <a-icon type="arrow-left" />
            关闭左侧
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </a-tab-pane>
  </a-tabs>
</template>

<script>
export default {
  model: {
    prop: 'pages',
    event: 'change'
  },
  props: {
    type: {
      type: String,
      default: 'editable-card'
    },
    activeTab: {
      type: String,
      default: ''
    },
    pages: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      activeKey: ''
    }
  },
  created () {
    this.handleRouteChange()
  },
  computed: {
    tabTitle () {
      return (page) => {
        let title = page.meta.title
        const last = [...page.meta.stack].pop()
        if (last) {
          title = `${title}-${last.meta.title}`
        }
        return title
      }
    }
  },
  watch: {
    '$route' () {
      this.handleRouteChange()
      this.$forceUpdate()
    },
    activeTab: {
      immediate: true,
      handler (n) {
        this.activeKey = n
      }
    }
  },
  methods: {
    onTabChange (key) {
      const page = this.pages.find(p => p.name == key)
      this.loadRoute(page)
      this.$emit('tabChange', page)
    },
    onEdit (key, action) {
      this[action](key)
      this.$emit('tabChange', this.pages[this.pages.length - 1])
    },
    refresh (page) {
      this.activeKey = page.name
      const index = this.pages.indexOf(page)
      if (page.meta.target) {
        this.pages.splice(index, 1)
        this.$nextTick(() => { this.pages.splice(index, 0, page) })
      } else {
        this.$router.reload()
      }
      this.$emit('tabChange', page)
    },
    closeOther (page) {
      this.pages.length = 0
      this.pages.push(page)
      this.loadRoute(page)
      this.$emit('tabChange', this.pages[this.pages.length - 1])
    },
    closeRight (page) {
      this.pages.length = this.pages.indexOf(page) + 1
      const current = this.pages.find(p => p.name == this.$router.name)
      if (!current) {
        this.loadRoute(this.pages[this.pages.length - 1])
      }
      this.$emit('tabChange', this.pages[this.pages.length - 1])
    },
    closeLeft (page) {
      this.pages.splice(0, this.pages.indexOf(page))
      const current = this.pages.find(p => p.name == this.$router.name)
      if (!current) {
        this.loadRoute(this.pages[this.pages.length - 1])
      }
      this.$emit('tabChange', this.pages[this.pages.length - 1])
    },
    remove (key) {
      const pages = [...this.pages]
      this.pages.length = 0
      pages.map(p => p.name !== key && this.pages.push(p))
      const current = this.pages.find(p => p.name == this.$router.name)
      if (!current) {
        this.loadRoute(this.pages[this.pages.length - 1])
      }
      // 更新路由保持
      this.$store.updateKeepAlive(this.pages)
    },
    loadRoute (page) {
      if (!page.meta.target) {
        if (page.meta.stack) {
          this.$router.push(page.meta.stack[page.meta.stack.length - 1])
        } else {
          this.$router.push(page)
        }
      }
    },
    getTabTitle (page) {
      let title = page.meta.title
      const last = [...page.meta?.stack || []].pop()
      if (last) {
        title = `${title}-${last.meta.title}`
      }
      return title
    },
    handleRouteChange () {
      if (this.$store.getTheme('tabs') == 'always') {
        this.alwaysOpenInNewTab()
      } else {
        this.openInSameTab()
      }
      // 更新路由保持
      this.$store.updateKeepAlive(this.pages)
    },
    alwaysOpenInNewTab () {
      const current = this.pages.find(p => p.meta.key == parent?.meta?.key || p.meta.key == this.$route.meta.key)
      this.activeKey = this.$route.meta.key
      if (!current) {
        this.pages.push(this.$route)
        this.$emit('tabChange', this.$route)
      }
    },
    openInSameTab () {
      const parent = this.getParentRoute(),
        current = this.pages.find(p => p.meta.key == parent?.meta?.key || p.meta.key == this.$route.meta.key)
      if (parent) {
        this.activeKey = parent.meta.key
        this.pushRouteStack(parent)
      } else {
        this.activeKey = this.$route.meta.key
      }
      if (!current) {
        this.pages.push(parent || this.$route)
        this.$emit('tabChange', parent || this.$route)
      }
    },
    getParentRoute (route) {
      const _route = route || this.$route
      let routes = [...(_route.meta.matched || _route.matched)]
      const r = routes.pop()
      if (r.meta?.type == '3' && routes.length > 0) {
        return routes.pop()
      }
    },
    pushRouteStack (parent) {
      parent.meta.stack = parent.meta.stack || []
      const stack = parent.meta.stack
      if (stack.find(r => r.name == this.$route.name)) {
        return
      }
      if (this.$route.path == parent.path || this.$route.path == parent.redirect) {
        stack.splice(0, 0, this.$route)
        stack.length = 1
        return
      }
      stack.push(this.$route)
    }
  }
}
</script>

<style>
</style>